import network,ntptime,time
from machine import RTC
from machine import Pin, I2C
import ssd1306
import urequests
import ujson




def ConnectNet(ssid ,password):
    mynetwork=network.WLAN(network.STA_IF)
    mynetwork.active(True)
    mynetwork.connect(ssid,password)
 
    while True:
        if(mynetwork.isconnected()):
            break
        else :
            time.sleep(1)
    print(mynetwork.ifconfig())




def RTC_Clock():
    datetime=rtc.datetime()
    print(datetime)
    display.fill(0)
    display.text("RTC Clock",0,0)
    display.text(str(datetime[0])+"-"+str(datetime[1])+"-"+str(datetime[2]),0,25)
    display.text(str(week[datetime[3]]),0,40)
    for i in range(4,7):
        if datetime[i]<10:
            timelist[i-4]="0"
        else:
            timelist[i-4]=""
    display.text(timelist[0]+str(datetime[4])+':'+timelist[1]+str(datetime[5])+':'+timelist[2]+str(datetime[6]),0,55)   
    display.show()



def Weather_display():
    url = 'https://api.seniverse.com/v3/weather/now.json?key=*********&location=宁波&language=zh-Hans&unit=c'
    #此处是调用和风天气的API接口，需要自己去申请key(把*替换成自己的key)，locaion根据自己的城市去修改
    response = urequests.get(url) 
    json_str=ujson.loads(response.text) 
    print(json_str['results'][0]['now']['text'])
    print(json_str['results'][0]['now']['temperature'])
    weather=json_str['results'][0]['now']['text']
    weather=weather_dict[weather]
    temperature=json_str['results'][0]['now']['temperature']
    
    display.fill(0)
    display.text("WeatherCondition",0,0)
    display.text("Location:ningbo",0,25)
    display.text("Weather:"+weather,0,40)
    display.text("Temperature:"+temperature,0,55)
    display.show()
    
    

if __name__ == "__main__":
    
    while True:
        ssid = '********'      #填写wifi的ID
        password ='********'   #填写wifi密码
        i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000)
        display= ssd1306.SSD1306_I2C(128, 64, i2c)
        week=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
        weather_dict = {'晴':'Sun', '雨':'Rain', '多云':'Cloud', '雪':'Snow', '阴':'Overcast'}
        timelist=["","",""]

        ConnectNet(ssid ,password)
        rtc = RTC()    
        ntptime.NTP_DELTA = 3155644800  
        ntptime.host = 'ntp1.aliyun.com' 
        ntptime.settime()  


        while True:
            RTC_Clock()
            time.sleep(3)
            Weather_display()
            time.sleep(3)
            
            
        tim=Timer(-1)
        tim.init(period=30000,mode=timer.PERIODIC,callback=init_time)
    



